package com.oren.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * Created by IntelliJ IDEA.
 * User: wangshiwei
 * Date: 2018/6/15
 * Time: 9:56
 * describe: 类加载器
 */
public final class ClassUtil {
    //日志
    private static final Logger LOGGER= LoggerFactory.getLogger(Class.class);

    /**
     * 获取类加载器
     * @return
     */
    public static ClassLoader getClassLoader(){
        return  Thread.currentThread().getContextClassLoader();
    }

    /**
     * 加载类
     * @param className 类的名称
     * @param isInit 是否已经加载过了
     * @return
     */
    public static Class<?> loadClass(String className,boolean isInit){
        Class<?> cls;
        try {
            cls=Class.forName(className,isInit,getClassLoader());
        } catch (ClassNotFoundException e) {
            LOGGER.error("load "+className+".class  failure "+e);
            throw  new RuntimeException(e);
        }
        return cls;
    }

    /**
     * 扫描包下面的所有类
     * @param packageName
     * @return
     */
    public static Set<Class<?>> getClassSet(String packageName){
        Set<Class<?>> classSet=new HashSet<Class<?>>();
        try {
        	//获取包下面的所有类的url
            Enumeration<URL> urls = getClassLoader().getResources(packageName.replace(".", "/"));
            //开始遍历
            while(urls.hasMoreElements()){
                URL url=urls.nextElement();
                if(url!=null){
                    String protocol=url.getProtocol();
                    if(protocol.equals("file")){
                        String packagePath=url.getPath().replaceAll("%20","");
                        addClass(classSet,packagePath,packageName);
                    }else if(protocol.equals("jar")){
                        JarURLConnection jarURLConnection=(JarURLConnection) url.openConnection();
                        if(jarURLConnection!=null){
                            JarFile jarFile=jarURLConnection.getJarFile();
                            if(jarFile!=null){
                                Enumeration<JarEntry> jarEntryEnumeration=jarFile.entries();
                                while (jarEntryEnumeration.hasMoreElements()){
                                    JarEntry jarEntry=jarEntryEnumeration.nextElement();
                                    String jarEntryName=jarEntry.getName();
                                    if(jarEntryName.endsWith(".class")){
                                        String className=jarEntryName.substring(0,jarEntryName.lastIndexOf(".")).replaceAll("/",".");
                                        doAddClass(classSet,className);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return classSet;
    }

    /**
     * 将所有扫描的class添加包中
     * @param classSet
     * @param packagePath
     * @param packageName
     */
    public static void addClass(Set<Class<?>> classSet, String packagePath, final String packageName){
        
    	//在改路径下获取所有文件
    	//FileFilter过滤器，只要class文件和文档
    	File[] files=new File(packagePath).listFiles(new FileFilter() {
            public boolean accept(File file) {
                boolean f=(file.isFile() && file.getName().endsWith(".class")) || file.isDirectory();
                return f;
            }
        });
    	//遍历每个文件
        for (File file:files) {
            String fileName=file.getName();
            if(file.isFile()){
            	//去掉.class后缀
                String className=fileName.substring(0,fileName.lastIndexOf("."));
                //如果包名为空，则加上包名
                if(!StringUtil.isEmpty(className)){
                    className=packageName+"."+className;
                }
                //加载类
                doAddClass(classSet,className);
            }else {
            	//这里对file是文件夹进行的操作
                String subPackagePath=fileName;
                if(!StringUtil.isEmpty(subPackagePath)){
                    subPackagePath=packagePath+"/"+subPackagePath;
                }
                String subPackageName=fileName;
                if(!StringUtil.isEmpty(subPackageName)){
                    subPackageName=packageName+"."+subPackageName;
                }
               addClass(classSet,subPackagePath,subPackageName);
            }
        }
    }

    /**
     * 加载真正的类
     * @param classSet
     * @param classPath
     */
    public static void doAddClass(Set<Class<?>> classSet,String classPath){
            Class<?> cls=loadClass(classPath,false);
        classSet.add(cls);
    }

}
